package com.syn.vr.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.gaoyi.basemodule.apiresult.ApiResultData;
import com.gaoyi.basemodule.baseCallback.OnResultListener;
import com.gaoyi.basemodule.baseUtil.SPUtil;
import com.gaoyi.basemodule.baseconstant.SPName;
import com.google.gson.reflect.TypeToken;
import com.syn.vr.constant.ApiStatus;
import com.syn.vr.db.entity.Record;
import com.syn.vr.repository.TagRepository;

import java.util.List;

public class SyncService extends Service {

    private TagRepository mRepository;

    @Override
    public void onCreate() {
        super.onCreate();
        mRepository = new TagRepository();
        loop();
    }

    private void loop() {
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(10 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                uploadTag();
            }
        }).start();
    }

    private void uploadTag() {
        if (TextUtils.isEmpty(SPUtil.getInstance().getString(SPName.TOKEN))) {
            return;
        }
        List<Record> records = mRepository.queryUnUpload();
        if (records == null || records.isEmpty()) {
            return;
        }
        uploadTag(records.get(0));
    }

    private void uploadTag(Record record) {
        mRepository.adds(record, new OnResultListener() {
            @Override
            public void onSuccess(Object apiResult) {
                ApiResultData<String> apiResultData = (ApiResultData<String>) apiResult;
                if (apiResultData.getStatus() == ApiStatus.SUCCESS) {
                    record.setUpload(1);
                    mRepository.update(record);
                } else {
                    record.setUpload(2);
                    mRepository.update(record);
                }
            }

            @Override
            public void onFails(Exception e) {

            }
        }, new TypeToken<ApiResultData<String>>() {
        }.getType());
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
